# -*- coding: utf-8 -*-
'''
@author: lowzoom
'''
import os
from collections import OrderedDict
import shutil
import main
import win32_util

# "我的文档"路径
MY_DOCUMENTS_PATH = win32_util.get_my_documents()

# 配置文件相关路径
fifa_path = os.path.join(MY_DOCUMENTS_PATH, 'FIFA 12')
file_name = 'buttonDataSetup.ini'
path = os.path.join(fifa_path, file_name)

# 按键对应设置
key_map = OrderedDict()

# 配置文件中的其他内容
lines_before = []
lines_after = []

def load():
	'''
	读取键位配置文件
	'''
	if not os.path.isfile(path):
		if not os.path.isdir(fifa_path):
			os.makedirs(fifa_path)
		shutil.copy(os.path.join(main.base_path, 'data', file_name), fifa_path)

	key_map.clear()
	del lines_before[:]
	del lines_after[:]

	with open(path, 'r') as button_data_file:

		# 跳到键盘的设置
		while True:
			line = button_data_file.readline()
			lines_before.append(line)
			if line.startswith('AddController "Keyboard"'):
				break

		# 将键盘的键位设置读进内存
		while True:
			line = button_data_file.readline()
			if line == '' or line.startswith('AddController'):
				lines_after.append(line)
				break

			parts = line.split()
			key_map[parts[-1]] = parts[-2]

		# 将剩下部分读进内存方便保存写入
		while True:
			line = button_data_file.readline()
			if line == '':
				break
			lines_after.append(line)

def save():
	with open(path, 'w') as button_data_file:
		button_data_file.writelines(lines_before)
		button_data_file.writelines(
			['\tAddMap {key} {button}\n'.format(key=key, button=btn)
			for btn, key in key_map.iteritems()])
		button_data_file.writelines(lines_after)

def set_key(btn_names, key_name):
	for btn in btn_names:
		key_map[btn] = key_name
